import * as PIXI from 'pixi.js';
export default class ShapeUtil{

    /**
     * 绘制虚线
     * @param $graphics 
     * @param $start 
     * @param $end 
     * @param $wdith 
     * @param $grap 
     */
    public static drawDash($graphics:PIXI.Graphics, $start:PIXI.Point, $end:PIXI.Point, $wdith:number = 5, $grap:number = 5):void
    {
        if (!$graphics || !$start || !$end || $wdith <= 0 || $grap <= 0) return;
        
        var ox:number = $start.x;
        var oy:number = $start.y;
        
        var radian:number = Math.atan2($end.y - oy, $end.x - ox);
        var cos:number = Math.cos(radian), sin:number = Math.sin(radian);
        var totalLen:number = ShapeUtil.getDistance($start, $end);
        var currLen:number = 0;
        var x:number, y:number;
        
        while (currLen <= totalLen)
        {
            x = ox + cos * currLen;
            y = oy + sin * currLen;
            $graphics.moveTo(x, y);
            
            currLen = Math.min(currLen + $wdith, totalLen);
            
            x = ox + cos * currLen;
            y = oy + sin * currLen;
            $graphics.lineTo(x, y);
            
            currLen += $grap;
        }
    }

    /**
     * 计算两点间距
     * @param $start 
     * @param $end 
     */
    public static getDistance($start:PIXI.Point, $end:PIXI.Point):number{
        var n = Math.sqrt(Math.pow(($start.x - $end.x), 2) + Math.pow(($start.y - $end.y), 2));
        return n;
    }

    /**
     * 计算多边形重心
     * @param pts 
     */
    public static gravity(pts:Array<PIXI.Point>):PIXI.Point
    {
        var acreage:number = 0, result:PIXI.Point = new PIXI.Point;
        for (var i = 1, l = pts.length; i <= l; i++)
        {
            var prevx:number = pts[i % l].x;
            var prevy:number = pts[i % l].y;
            var nextx:number = pts[i - 1].x;
            var nexty:number = pts[i - 1].y;
            var plus:number = 0.5 * (prevx * nexty - prevy * nextx);
            acreage += plus;
            result.x += plus * (prevx + nextx) / 3;
            result.y += plus * (prevy + nexty) / 3;
        }
        result.x /= acreage;
        result.y /= acreage;
        return result;
    }

    public static getBounds(list: Array<PIXI.Point>):PIXI.Bounds{
        var bounds:PIXI.Bounds = new PIXI.Bounds();
        list.forEach(i => bounds.addPoint(i));
        return bounds;
    }
		
}